<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Validation\Rule;
use Dcat\Admin\Traits\HasDateTimeFormatter;

class StoreCategory extends Model
{
    use HasDateTimeFormatter;
    
    protected $table = 'ims_yz_store_category';
    protected $guarded = [''];
    protected $appends = ['open_name'];
    
    const PAGE_SIZE = 20;

    /**
     * 获取分类列表
     */
    public static function getList()
    {
        return self::select();
    }
    
    /**
     * 根据ID获取分类
     */
    public static function getCategoryById($id)
    {
        return self::select()->byId($id);
    }
    
    /**
     * 按ID筛选
     */
    public function scopeById($query, $id)
    {
        return $query->where('id', $id);
    }
    
    /**
     * 按开启状态筛选
     */
    public function scopeByOpen($query, $is_open)
    {
        return $query->where('is_open', $is_open);
    }
    
    /**
     * 按启用状态筛选（别名方法）
     */
    public function scopeEnabled($query)
    {
        return $query->where('is_open', 1);
    }
    
    /**
     * 按排序字段排序
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort', 'asc');
    }
    
    /**
     * 获取开启状态名称
     */
    public function getOpenNameAttribute()
    {
        if ($this->is_open == 0) {
            $status_name = '关闭';
        } else {
            $status_name = '开启';
        }
        return $status_name;
    }
    
    /**
     * 属性名称
     */
    public function attributeNames()
    {
        return [
            'sort' => '排序',
            'thumb' => '分类图片'
        ];
    }
    
    /**
     * 验证规则
     */
    public function rules()
    {
        return [
            'sort' => 'integer',
            'thumb' => 'required'
        ];
    }
    
    /**
     * 插入默认分类
     */
    public static function insertDefaultCategory()
    {
        $categorys = self::getList()->get();
        if ($categorys->isEmpty()) {
            self::create([
                'sort' => 1,
                'name' => '默认分类',
                'thumb' => '',
                'is_open' => 1
            ]);
        }
    }
    
    /**
     * 与门店的关系
     */
    public function stores()
    {
        return $this->hasMany(Store::class, 'category_id');
    }
}
